package carnet;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import exceptions.*;

public class Champ {
	private String nom;
	private String valeur;
	public enum Type{
		Default, Telephone, Email;
	};
	private Type type;
	
	public Champ(String n, String v, Type t) throws Exception{
		// Set
		nom = n;
		valeur = v;
		type = t;
		
		// Verification
		if(t == Type.Telephone)
			if(!isTelephone())
				throw new NotTelephoneException();
		if(t == Type.Email)
			if(!isEmailAdress())
				throw new NotEmailException();
	}
	
	public Champ(Champ c) throws Exception{
		// Verification
		if(c.type == Type.Telephone)
			if(!isTelephone())
				throw new NotTelephoneException();
		if(c.type == Type.Email)
			if(!isEmailAdress())
				throw new NotEmailException();
		
		// Set
		nom = c.getNom();
		valeur = c.getValeur();
		type = c.getType();
	}	
	
	public boolean isEmailAdress(){
		Pattern p = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$");
		Matcher m = p.matcher(valeur.toUpperCase());
		return m.matches();
	}
	
	public boolean isTelephone(){
		if(valeur.length() == 10){
			Pattern p = Pattern.compile("[0-9]*");
			Matcher m = p.matcher(valeur);
			return m.matches();
		}
		return false;
	}
	
	// -------------------------------------
	// Getters / Setter
	public String getNom() {
		return nom;
	}

	public void setNom(String nom) {
		this.nom = nom;
	}

	public String getValeur() {
		return valeur;
	}

	public void setValeur(String valeur) {
		this.valeur = valeur;
	}
	
	public Type getType() {
		return type;
	}

	public void setType(Type type) {
		this.type = type;
	}

	// Visitor
	public void accept(Visitor v){
		v.visitChamp(this);	
	}
}
